/**
 * ****************************************************************************
 * Project: RoboBridge
 * ----------------------------------------------------------------------------
 * -------------------------- [c]2012 - KrawallMann ---------------------------
 * ---------------------- http://www.krawallmann.de.tc/ -----------------------
 * ****************************************************************************
 * File: ThreadedReader.java Package: tc.de.krawallmann.robobridge.communication
 * Version: 1.0 Author(s): KrawallMann
 * ****************************************************************************
 * Description:
 * ****************************************************************************
 */
package tc.de.krawallmann.robobridge.communication;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.logging.Level;

import tc.de.krawallmann.robobridge.util.Log;

/**
 * The Class ThreadedReader asynchronously reads from an InputStream using a
 * Thread.<br/>
 * 
 * @author KrawallMann
 * @version 1.0
 */
public class ThreadedReader extends Reader implements Runnable {

	/** The count. */
	private static int count;

	/** The read. */
	private transient boolean read = true;

	/** The thread. */
	private transient Thread thread;

	/*
	 * (non-Javadoc)
	 * @see communication.Reader#close()
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void close() {
		read = false;
		thread.stop();
		super.close();
	}

	/*
	 * (non-Javadoc)
	 * @see communication.Reader#connect(java.io.InputStream)
	 */
	@Override
	public void connect(final InputStream inputStream) {
		super.connect(inputStream);
		thread = new Thread(this);
		++ThreadedReader.count;
		read = true;
		thread.setName("ThreadedReader #" + ThreadedReader.count);
		thread.start();
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		while (read) {
			try {
				readLine();
			} catch (final SocketException exc) {
				Log.log(Level.WARNING, getClass(), "run",
						"Exception while reading - prpbably a timeout - {0}!", exc.getMessage());
				read = false;
			} catch (final IOException exc) {
				if (exc.getMessage().contains("Software caused connection abort: recv failed!")) {
					throw new IllegalStateException("Exception while reading - maybe timeout?", exc);
				}
				Log.log(Level.WARNING, getClass(), "run", "Exception while reading - {0}!",
						exc.getMessage());
			}
		}
	}

}
